package com.yingjie.yingjieuser.service.impl;

import com.yingjie.commonbase.commons.Constents;
import com.yingjie.commonbase.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yingjie.yingjieuser.mapper.UserMapper;
import com.yingjie.yingjieuser.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【user(微信登录用户表)】的数据库操作Service实现
* @createDate 2025-02-19 13:27:33
*/
@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;
    /*
     * wx小程序登录
     * */
    public Object wxLogin(Map<String, Object> params) throws JsonProcessingException {
        String code = params.get("wxCode").toString();
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(
                "https://api.weixin.qq.com/sns/jscode2session?appid="+ Constents.wx_appid
                        +"&secret=" + Constents.wx_secret
                        +"&js_code="+code
                        +"&grant_type=authorization_code",
                String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        Map forMap = objectMapper.readValue(forObject, Map.class);

        String openid = (String) forMap.get("openid");
        String nickName = params.get("nickName").toString();
        String avatarUrl = params.get("avatarUrl").toString();
        Integer gender = (Integer) params.get("gender");

        if(openid!=null){
            User user1 = userMapper.selectByOpenid(openid);
            //如果用户存在返回用户信息
            if(user1!=null){
                //修改用户
                User setUser = new User();
                setUser.setUserId(user1.getUserId());
                setUser.setGender(gender);
                setUser.setNickname(nickName);
                setUser.setAvatarUrl(avatarUrl);
                setUser.setUpdatedAt(new Date());
                userMapper.setUserInfo(setUser);
                return setUser;
            }

            User user = new User();
            user.setOpenid(openid);
            //用户不存在创建新用户
            Date date = new Date();
            user.setCreatedAt(date);
            user.setUpdatedAt(date);
            user.setUpdatedAt(date);
            user.setNickname(nickName);
            user.setAvatarUrl(avatarUrl);
            user.setGender(gender);
            int key = userMapper.insertSelective(user);
            forMap.put("userId",user.getUserId());
        }

        return forMap;
    }

    @Override
    public User getUserInfo(Integer userId) {
        return userMapper.getUserInfo(userId);
    }
}




